package com.hzw.net.page

import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.hzw.net.annotation.BindViewModel
import com.hzw.net.vm.AbsViewModel
import com.hzw.net.vm.event.Event

/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/11/5 16:25
 *
 * @Description:    主要用于使用viewModel的Activity
 *
 */
abstract class BaseViewModelActivity<VB : ViewBinding> : BaseActivity<VB>() {

    override fun initSpecialEvent() {
        super.initSpecialEvent()
        initViewModel()
    }

    private fun initViewModel() {
        javaClass.declaredFields
            .filter { field ->
                field.isAnnotationPresent(BindViewModel::class.java)
            }
            .forEach { field ->
                val viewModel: AbsViewModel =
                    ViewModelProvider(this).get(field.getAnnotation(BindViewModel::class.java)!!.model.java)
                initCommonEvent(viewModel)
                field.set(this, viewModel)
            }
    }


    private fun initCommonEvent(viewModel: AbsViewModel) {
        viewModel.eventLiveData.observe(this, { commonEvent ->
            when (commonEvent.event) {
                Event.SHOW_LOADING -> showLoading(commonEvent.showLoadingHideOther)
                Event.HIDE_LOADING -> hideLoading()
                Event.CONTENT -> showContent()
                Event.ERROR -> showError()
                Event.EMPTY -> showEmpty()
                Event.TOAST -> showToast(commonEvent.msg)
                Event.SPECIAL -> handleSpecialEvent(commonEvent.code)
            }
        })
    }
}